package com.sutong.gateway.utils;

import cn.hutool.json.JSONUtil;
import com.sutong.common.result.BaseResponse;
import com.sutong.common.result.ErrorCode;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

/**
 * 响应工具类
 *
 * @author sutong
 * @date 2024-07-14 19:09
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class WebFluxResultUtils {
    public static Mono<Void> success(ServerHttpResponse response, Object data) {
        return error(response, MediaType.APPLICATION_JSON_VALUE, HttpStatus.OK, 0, null, data);
    }

    public static Mono<Void> error(ServerHttpResponse response, ErrorCode errorCode) {
        return error(response, MediaType.APPLICATION_JSON_VALUE, HttpStatus.OK, errorCode.getCode(), errorCode.getMessage(), null);
    }

    public static Mono<Void> error(ServerHttpResponse response, String message) {
        return error(response, MediaType.APPLICATION_JSON_VALUE, HttpStatus.OK, 500, message, null);
    }

    public static Mono<Void> error(ServerHttpResponse response, int code, String message) {
        return error(response, MediaType.APPLICATION_JSON_VALUE, HttpStatus.OK, code, message, null);
    }

    public static Mono<Void> error(ServerHttpResponse response, String contentType, HttpStatus status, int code, String message, Object data) {
        response.setStatusCode(status);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, contentType);
        BaseResponse<Object> result = new BaseResponse<>(code, data, message);
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSONUtil.toJsonStr(result).getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }

}
